// ==========================================================================
// gin-sns自动生成业务逻辑层相关代码，只生成一次，按需修改,再次生成不会覆盖.
// date：2021-02-21 13:45:54 +0800 CST
// path: app/service/module/unlike_service.go
// author：jon
// ==========================================================================
package module

import (
	"errors"
	"gin-sns/app/dao/module/unlike"
	"gin-sns/app/model/constants"
	unlikeModel "gin-sns/app/model/module/unlike"
	"time"

	"github.com/gin-gonic/gin"

	"gin-sns/app/ginframe/utils/convert"
	"gin-sns/app/ginframe/utils/page"
)

var UnlikeService = newUnlikeService()

func newUnlikeService() *unlikeService {
	return &unlikeService{}
}

type unlikeService struct {
}

//根据主键查询数据
func (s *unlikeService) SelectRecordById(id int64) (*unlikeModel.Entity, error) {
	return unlike.UnlikeDao.SelectById(id)
}

//
func (s *unlikeService) SelectRecordsIn(idarr []int64) ([]unlikeModel.Entity, error) {

	list, err := unlike.UnlikeDao.FindIn("id", idarr)
	if list != nil && len(list) > 0 {
		err = errors.New("not found")
		list = nil
	}
	return list, err
}

//根据主键删除数据
func (s *unlikeService) DeleteRecordById(id int64) bool {
	return unlike.UnlikeDao.DeleteById(id)
}

//批量删除数据记录
func (s *unlikeService) DeleteRecordByIds(ids string) int64 {
	ida := convert.ToInt64Array(ids, ",")
	result, err := unlike.UnlikeDao.DeleteBatch(ida...)
	if err != nil {
		return 0
	}
	return result
}

//添加数据
func (s *unlikeService) AddSave(req *unlikeModel.AddReq, ctx *gin.Context) (int64, error) {
	var entity unlikeModel.Entity

	//entity.Id = req.Id
	entity.UserId = req.UserId
	entity.EntityType = req.EntityType
	entity.EntityId = req.EntityId
	entity.Status = req.Status
	entity.CreateTime = time.Now()
	//entity.CreateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user != nil {
	//	entity.CreateBy = user.LoginName
	//}

	_, err := unlike.UnlikeDao.Insert(&entity)
	return entity.Id, err
}

//修改数据
func (s *unlikeService) EditSave(req *unlikeModel.EditReq, ctx *gin.Context) (int64, error) {
	entity := &unlikeModel.Entity{Id: req.Id}
	ok, err := unlike.UnlikeDao.FindOne(entity)

	if err != nil {
		return 0, err
	}

	if !ok {
		return 0, errors.New("数据不存在")
	}

	entity.UserId = req.UserId
	entity.EntityType = req.EntityType
	entity.EntityId = req.EntityId
	entity.Status = req.Status
	//entity.UpdateTime = time.Now()
	//entity.UpdateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user == nil {
	//	entity.UpdateBy = user.LoginName
	//}

	return unlike.UnlikeDao.Update(entity)
}

//根据条件查询数据
func (s *unlikeService) SelectListAll(params *unlikeModel.SelectPageReq) ([]unlikeModel.Entity, error) {
	return unlike.UnlikeDao.SelectListAll(params)
}

//根据条件分页查询数据
func (s *unlikeService) SelectListByPage(params *unlikeModel.SelectPageReq) ([]unlikeModel.Entity, *page.Paging, error) {
	return unlike.UnlikeDao.SelectListByPage(params)
}

// 导出excel
func (s *unlikeService) Export(param *unlikeModel.SelectPageReq) (string, error) {
	head := []string{"", "用户id", "实体类型", "实体id", "0未审核 1正常状态 2审核未通过 3删除", "添加时间"}
	col := []string{"id", "user_id", "entity_type", "entity_id", "status", "create_time"}
	return unlike.UnlikeDao.SelectListExport(param, head, col)
}

// 统计数量
func (s *unlikeService) CountAnswerUnike(id int64) int64 {

	return unlike.UnlikeDao.Count(constants.EntityTypeAnswer, id)
}

func (s *unlikeService) CountCommentUnike(id int64) int64 {

	return unlike.UnlikeDao.Count(constants.EntityTypeComment, id)
}

// 统计数量
func (s *unlikeService) Count(entityType int, entityId int64) int64 {

	return unlike.UnlikeDao.Count(entityType, entityId)

}

// 最近点赞
func (s *unlikeService) Recent(entityType int, entityId int64, count int) []unlikeModel.Entity {
	list, _ := unlike.UnlikeDao.GetNewestUnlikes(entityType, entityId, count)

	return list
}

// Exists 是否点赞
func (s *unlikeService) Exists(userId int64, entityType int, entityId int64) bool {

	entity := &unlikeModel.Entity{
		UserId:     userId,
		EntityType: entityType,
		EntityId:   entityId,
	}

	have, _ := unlike.UnlikeDao.FindOne(entity)

	return have

}

// 是否点赞，返回已点赞实体编号
func (s *unlikeService) IsUnliked(userId int64, entityType string, entityIds []int64) []int64 {

	return unlike.UnlikeDao.IsUnliked(userId, entityType, entityIds)
}

// 话题点赞
func (s *unlikeService) AnswerUnlike(userId int64, answerId int64) error {
	answer, _ := AnswerService.SelectRecordById(answerId)
	if answer == nil || answer.Status != constants.StatusOk {
		return errors.New("话题不存在")
	}

	if err := s.unlike(userId, constants.EntityTypeAnswer, answerId); err != nil {
		return err
	}

	// 更新点赞数
	AnswerService.IncrUnlikeCount(answerId)

	return nil
}

// 话题点赞
func (s *unlikeService) CommentUnlike(userId int64, commentId int64) error {
	comment, _ := CommentService.SelectRecordById(commentId)
	if comment == nil || comment.Status != constants.StatusOk {
		return errors.New("话题不存在")
	}

	if err := s.unlike(userId, constants.EntityTypeComment, commentId); err != nil {
		return err
	}

	// 更新点赞数
	CommentService.IncrUnlikeCount(commentId)

	return nil
}

func (s *unlikeService) unlike(userId int64, entityType int, entityId int64) error {
	// 判断是否已经点赞了
	if s.Exists(userId, entityType, entityId) {
		return errors.New("已点赞")
	}
	// 点赞
	entity := &unlikeModel.Entity{
		UserId:     userId,
		EntityType: entityType,
		EntityId:   entityId,
		CreateTime: time.Now(),
	}

	_, err := unlike.UnlikeDao.Insert(entity)

	return err
}
